from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.models import User
from .models import UserProfile, UserActivity
from .forms import UserProfileForm
from story.models import Story
from interactive.models import Like, Favorite, Report


def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            # 创建用户资料
            UserProfile.objects.create(user=user)
            # 记录用户活动
            UserActivity.objects.create(
                user=user,
                activity_type='register',
                activity_data={'username': user.username}
            )
            # 不再自动登录用户
            messages.success(request, '注册成功！请使用您的账号密码登录。')
            return redirect('user:login')
        else:
            # 表单验证失败，确保错误消息显示
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f"{field}: {error}")
    else:
        form = UserCreationForm()
    
    return render(request, 'user/register.html', {'form': form})


def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                # 记录用户活动
                UserActivity.objects.create(
                    user=user,
                    activity_type='login',
                    activity_data={'username': user.username}
                )
                messages.success(request, f'欢迎回来，{username}！')
                return redirect('home')
        else:
            # 表单验证失败，确保错误消息显示
            if form.non_field_errors():
                for error in form.non_field_errors():
                    messages.error(request, error)
            else:
                for field, errors in form.errors.items():
                    for error in errors:
                        messages.error(request, f"{field}: {error}")
    else:
        form = AuthenticationForm()
    
    response = render(request, 'user/login.html', {'form': form})
    return response


@login_required
def logout_view(request):
    try:
        # 记录用户活动
        UserActivity.objects.create(
            user=request.user,
            activity_type='logout',
            activity_data={'username': request.user.username}
        )
        logout(request)
        messages.info(request, '您已成功登出。')
    except Exception as e:
        # 记录错误但仍然尝试注销用户
        print(f"退出登录时发生错误: {str(e)}")
        try:
            logout(request)
        except:
            pass
        messages.warning(request, '退出过程中发生错误，但您已被登出。')
    
    return redirect('home')


@login_required
def profile(request):
    user_profile, created = UserProfile.objects.get_or_create(user=request.user)
    
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=user_profile)
        if form.is_valid():
            form.save()
            # 记录用户活动
            UserActivity.objects.create(
                user=request.user,
                activity_type='update_profile',
                activity_data={'updated_fields': list(form.changed_data)}
            )
            messages.success(request, '个人资料已更新！')
            return redirect('user:profile')
    else:
        form = UserProfileForm(instance=user_profile)
    
    # 获取用户的故事
    user_stories = Story.objects.filter(author=request.user).order_by('-created_at')
    
    # 获取用户的观看记录
    view_activities = UserActivity.objects.filter(
        user=request.user, 
        activity_type='view_story'
    ).order_by('-created_at')[:10]
    
    view_history = []
    for activity in view_activities:
        story_id = activity.activity_data.get('story_id')
        if story_id:
            try:
                story = Story.objects.get(id=story_id)
                view_history.append({
                    'story': story,
                    'timestamp': activity.created_at
                })
            except Story.DoesNotExist:
                pass
    
    # 获取用户的点赞记录
    likes = Like.objects.filter(user=request.user).select_related('story').order_by('-created_at')[:10]
    
    # 获取用户的收藏记录
    favorites = Favorite.objects.filter(user=request.user).select_related('story').order_by('-created_at')[:10]
    
    # 获取用户的举报记录
    reports = Report.objects.filter(reporter=request.user).select_related('story').order_by('-created_at')[:10]
    
    context = {
        'form': form,
        'user_profile': user_profile,
        'user_stories': user_stories,
        'view_history': view_history,
        'likes': likes,
        'favorites': favorites,
        'reports': reports,
        'active_tab': request.GET.get('tab', 'profile')
    }
    return render(request, 'user/profile.html', context)


def user_profile(request, username):
    user = get_object_or_404(User, username=username)
    profile = user.profile
    stories = Story.objects.filter(author=user, is_draft=False).order_by('-created_at')

    # 记录查看用户资料的活动
    if request.user.is_authenticated and request.user != user:
        UserActivity.objects.create(
            user=request.user,
            activity_type='view_profile',
            activity_data={'viewed_user': username}
        )

    context = {
        'profile_user': user,
        'profile': profile,
        'stories': stories,
    }
    return render(request, 'user/user_profile.html', context)
